#include "goomba.h"
#include "player.h"
#include "smallmario.h"
#include "firemario.h"
#include <QPainter>
#include <QDebug>

// 构造函数：初始化 Goomba（蘑菇敌人）
Goomba::Goomba(QRectF platformRect, int direction, QGraphicsItem *parent)
    : QGraphicsItem(parent), mCurrentFrame3(), mPlatform(platformRect), mDirection(direction)
{
    setFlag(ItemClipsToShape);                            // 限制绘图区域在 boundingRect 范围内
    mPixmap3 = QPixmap(":images/redgoombas.png");            // 加载动画贴图

    // 定时器：每 100ms 更新一帧动画 + 移动 + 碰撞检测
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(nextFrame()));
    timer->start(100);
}

// 每次定时触发：移动、动画更新、碰撞检测
void Goomba::nextFrame() {
    // 切换帧动画（帧宽 54px）
    mCurrentFrame3 += 54;
    if (mCurrentFrame3 >= 862)
        mCurrentFrame3 = 0;

    // 到达平台边界，反转方向并镜像贴图
    if (this->pos().x() < mPlatform.x() || this->pos().x() > mPlatform.x() + mPlatform.width()) {
        mDirection = -mDirection;
        setTransform(QTransform(-mDirection, 0, 0, 1, boundingRect().width(), 0));
    }

    // 每帧沿当前方向移动
    setPos(this->pos().x() + (mDirection * 7), this->pos().y());

    // ====== 碰撞检测开始 ======
    QList<QGraphicsItem *> colliding_items = collidingItems();

    // 撞到 Player：触发变小逻辑
    for (int i = 0; i < colliding_items.size(); ++i) {
        if (typeid(*(colliding_items[i])) == typeid(Player)) {
            emit marioSizeStatus(0);  // 触发信号，通知外部逻辑
            delete colliding_items[i];  // 删除当前角色（Player）
            qDebug() << "Mario deleted small mario added";
            delete this;  // 删除自己
            return;
        }
    }

    // 撞到 SmallMario：直接死亡
    for (int i = 0; i < colliding_items.size(); ++i) {
        if (typeid(*(colliding_items[i])) == typeid(SmallMario)) {
            emit marioSizeStatus(1);  // 发信号通知死亡
            delete colliding_items[i];
            qDebug() << "small mario dead";
            delete this;
            return;
        }
    }

    // 撞到 FireMario：变为小马里奥
    for (int i = 0; i < colliding_items.size(); ++i) {
        if (typeid(*(colliding_items[i])) == typeid(Fireflyplayer)) {
            emit marioSizeStatus(6);  // 通知变为小马里奥
            delete colliding_items[i];
            qDebug() << "Fire mario deleted small mario added";
            delete this;
            return;
        }
    }
}

// 返回图元边界，用于绘制与碰撞检测
QRectF Goomba::boundingRect() const {
    return QRectF(0, 0, 52, 50);  // 帧尺寸 52×50
}

// 绘图函数：每帧调用，绘制当前帧图像
void Goomba::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
    painter->drawPixmap(0, 0, mPixmap3, mCurrentFrame3, 0, 52, 50);  // 从图集 mPixmap3 中绘制当前帧
    setTransformOriginPoint(boundingRect().center());  // 设置旋转中心
    Q_UNUSED(widget);
    Q_UNUSED(option);
}

// 类型识别函数（自定义 Qt 类型值）
int Goomba::type() const {
    return Type;
}

void Goomba::pause() {
//    if (moveTimer) moveTimer->stop();
//    paused = true;
}

void Goomba::resume() {
//    if (moveTimer) moveTimer->start(100);
//    paused = false;
}
